package com.xishu.service;

import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;
import com.googlecode.concurrentlinkedhashmap.Weighers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

public class LockService {
    private static Logger logger = LoggerFactory.getLogger(LockService.class);
    private static LockService instance = new LockService();

    private LockService() {
    }

    public static LockService getInstance() {
        return instance;
    }

    private Map<String, Object> lockMap = new ConcurrentLinkedHashMap.Builder<String, Object>()
            .maximumWeightedCapacity(10000).weigher(Weighers.singleton()).build();

    /**
     * 获取锁
     *
     * @param key
     * @return
     */
    public Object getLock(String key) {
        long startTime = System.currentTimeMillis();
        logger.info("start to get lock {}", key);
        Object lock = lockMap.get(key);

        if (lock != null) {
            logger.info("get the lock {} time is {}", key, System.currentTimeMillis() - startTime);
            return lock;
        }

        synchronized (this) {
            lock = new Object();
            lockMap.put(key, lock);
            logger.info("get the lock {} time is {}", key, System.currentTimeMillis() - startTime);
            return lock;
        }
    }
}
